var page = require('webpage').create()
var end_time = null,
	first_response=null,
	start_time = Date.now(),
	finished=false,
	page_loaded = false;

page.onConsoleMessage = function(msg) {
    console.log('console: ' + msg);
};
page.viewportSize = {
  width: 1024,
  height: 768*3
}

page.onInitialized = function() {

};

page.onLoadFinished = function(status) {
	page_loaded = true;
	console.log(status)
	end_time = Date.now() + 1000;
    setTimeout(make_result, 1000+10, page);     
};

page.onResourceRequested = function(request) {
  console.log("Starting request: #"+request.id+" ["+request.method+"]");
  end_time = null;
};

page.onResourceReceived = function(response) {
  console.log("Request finished: #"+response.id+" ["+response.status+"]");
  if (first_response === null && response.status != 301 && response.status != 302) {
    first_response = response;
  }
  if (page_loaded) {
    console.log("waiting "+1000+"ms before finished.");
    end_time = Date.now() + 1000;
    setTimeout(make_result, 1000+10, page);
  }
}

setTimeout(make_result, 20000 + 100, page);

page.open("https://www.jd.com")

function make_result(page) {
      if (finished) {
        return;
      }
      if (Date.now() - start_time < 20000) {
        if (!!!end_time) {
          return;
        }
        if (end_time > Date.now()) {
          setTimeout(make_result, Math.min(Date.now() - end_time, 100), page);
          return;
        }
      }
      
      var result = {};
      try {
      	console.log("进入到make_result!!!")
        result = _make_result(page);
        page.close();
        finished = true;
      } catch (e) {
        result = {
          content: page.content || "",
        }
        phantom.exit()
      }
      var body = JSON.stringify(result, null, 2);
      // console.log("！！！ 这是body：" + body);
      var t = /product_item_name/;
      if(t.test(body)){
        console.log("包含")
      }else{
        console.log("不包含")
      }
    }

    function _make_result(page) {
      if (first_response === null) {
        throw "Timeout before first response.";
      }

      var cookies = {};
      page.cookies.forEach(function(e) {
        cookies[e.name] = e.value;
      });

      var headers = {};
      if (first_response.headers) {
        first_response.headers.forEach(function(e) {
          headers[e.name] = e.value;
        });
      }

      return {
        content:  page.content,
      }
    }